{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Backblaze数据实验\n",
    "## 2. IsoForest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.linear_model import SGDOneClassSVM\n",
    "from sklearn.svm import OneClassSVM\n",
    "from sklearn.preprocessing import StandardScaler, MinMaxScaler\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.ensemble import IsolationForest\n",
    "\n",
    "data = np.load(r'data.npz', allow_pickle=True)\n",
    "X = data['X']\n",
    "Y = data['Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "from sklearn.model_selection import train_test_split\n",
    "# 正常样本\n",
    "X_data1 = X[Y==0]\n",
    "Y_data1 = np.zeros((len(X_data1),1))\n",
    "\n",
    "# 异常样本\n",
    "X_data2 = X[Y==1]\n",
    "Y_data2 = np.ones((len(X_data2),1))\n",
    "\n",
    "x_train, x_test, y_train, y_test = train_test_split(X_data1, Y_data1, train_size=0.8, test_size=0.2, random_state=1)\n",
    "\n",
    "x_test = np.concatenate((x_test, X_data2), axis=0)\n",
    "y_test = np.concatenate((y_test, Y_data2), axis=0)\n",
    "\n",
    "del X_data1, Y_data1, X_data2, Y_data2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.ensemble import IsolationForest\n",
    "debug = False\n",
    "if debug:\n",
    "    for contamination in (1e-5, 1e-4, 1e-3,): # 2e-5, 3e-5, 1e-4, 1e-3, 1e-2, 0.1, 0.5, 2e-5, 3e-5,\n",
    "        clf = IsolationForest(n_estimators=100, max_samples='auto', contamination=contamination)\n",
    "\n",
    "        clf.fit(x_train)\n",
    "        preds_train = clf.predict(x_train)\n",
    "        err_train = sum(preds_train==-1)/len(preds_train)\n",
    "        print(contamination, \"err_train:\", err_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "err_train: 0.0010037112010796221\n"
     ]
    }
   ],
   "source": [
    "contamination = 1e-3\n",
    "clf = IsolationForest(n_estimators=200, max_samples='auto', contamination=contamination, max_features=1.0)\n",
    "\n",
    "clf.fit(x_train)\n",
    "preds_train = clf.predict(x_train)\n",
    "err_train = sum(preds_train==-1)/len(preds_train)\n",
    "print(\"err_train:\", err_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Classification report for classifier \n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "         0.0     0.9799    0.9989    0.9893     59280\n",
      "         1.0     0.7958    0.1788    0.2920      1482\n",
      "\n",
      "    accuracy                         0.9789     60762\n",
      "   macro avg     0.8878    0.5888    0.6406     60762\n",
      "weighted avg     0.9754    0.9789    0.9723     60762\n",
      "\n",
      "\n",
      "Confusion matrix:\n",
      "[[59212    68]\n",
      " [ 1217   265]]\n"
     ]
    }
   ],
   "source": [
    "preds = clf.predict(x_test)\n",
    "preds[preds==1] = 0\n",
    "preds[preds==-1] = 1\n",
    "\n",
    "from sklearn import metrics\n",
    "print(\"Classification report for classifier \\n %s\\n\"\n",
    "      % ( metrics.classification_report(y_test, preds, digits=4)))\n",
    "print(\"Confusion matrix:\\n%s\" % metrics.confusion_matrix(y_test, preds))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.876312744613272"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "scores = clf.score_samples(x_test)\n",
    "metrics.roc_auc_score(y_test, -scores)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py310",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
